package com.demo.swingquickticket.util;

import java.io.*;

public class SerializeUtil {

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }

        ObjectOutputStream oout = null;
        ByteArrayOutputStream bout = null;

        try {
            bout = new ByteArrayOutputStream();
            oout = new ObjectOutputStream(bout);
            oout.writeObject(object);
            byte[] bytes = bout.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bout != null) {
                    bout.close();
                }
                bout = null;
                if (oout != null) {
                    oout.close();
                }
                oout = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        ByteArrayInputStream bin = null;
        ObjectInputStream oin = null;

        try {
            bin = new ByteArrayInputStream(bytes);
            oin = new ObjectInputStream(bin);
            return oin.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bin != null) {
                    bin.close();
                }
                bin = null;
                if (oin != null) {
                    oin.close();
                }
                oin = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
